import { app, shell, BrowserWindow, ipcMain, Menu, dialog } from 'electron'
import log from 'electron-log'
import path, { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png??asset&asarUnpack'
import simulator from '../../resources/LVGL.Simulator.exe?asset&asarUnpack'
import ChineseSimplified from '../../resources/font_1.ttf?asset&asarUnpack'
import configJson from '../../resources/config.json?commonjs-external&asset&asarUnpack'
import fs, { appendFileSync } from 'fs'
import { store } from './store'
import { formatText } from 'lua-fmt'
import { SerialPort } from 'serialport'
import {
  ButtonGenerator,
  LabelGenerator,
  BorderLabelGenerator,
  InitPageGenerator,
  OnControlNotifyGenerator,
  OnSystickUiGenerator,
  ImageGenerator,
  QrCodeGenerator,
  ModbusDataLabelGenerator,
  UserDataLableGenerator,
  ModbusStringLabelGenerator,
  UserDataStringLabelGenerator,
  ModbusDataInputGenerator,
  UserDataInputGenerator,
  ModbusStringInputGenerator,
  UserDataStringInputGenerator,
  BarGenerator,
  SliderGenerator,
  SwitchGenerator,
  LedGenerator,
  ComboboxGenerator,
  GifGenerator,
  SoundGenerator,
  OnControlNotifyUiGenerator,
  ModuleGenerator,
  TableGenerator,
  Gif2Generator,
  SlidePageGenerator
} from './lua-api'
// import { spawn } from 'child_process'
import cmd from 'node-cmd'
// import { id } from 'element-plus/es/locale'
// eslint-disable-next-line no-unused-vars
let currentworkspace = ''
// eslint-disable-next-line no-unused-vars
let currentworkconfig = ''

let mainWindow = null

let initConfigName = 'init.json'

log.transports.file.file = path.join(__dirname, 'main.log')

app.on('second-instance', (event, commandLine, workingDirectory) => {
  // 检查是否有项目文件路径传入
  const projectFilePath = commandLine.find((arg) => arg.endsWith(initConfigName))
  if (projectFilePath) {
    // 激活已有窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
      // 加载新项目
      setCurrentWorkSpace(projectFilePath)
    }
  }
})

// 存储当前端口列表
let currentPorts = []

// 定时检查串口变化（每2秒检查一次）
setInterval(async () => {
  try {
    const newPorts = await SerialPort.list()
    const portsChanged = JSON.stringify(newPorts) !== JSON.stringify(currentPorts)

    if (portsChanged) {
      currentPorts = newPorts
      // 通知所有窗口串口列表已更新
      BrowserWindow.getAllWindows().forEach((win) => {
        win.webContents.send('serial-ports-updated', newPorts)
      })
    }
  } catch (error) {
    console.error('串口检测错误:', error)
  }
}, 2000) // 2秒检测一次

const Menus = [
  {
    label: '文件',
    submenu: [
      {
        label: '打开',
        role: 'help',
        click: function () {
          dialog
            .showOpenDialog({
              properties: ['openFile'],
              title: '选择工程文件',
              filters: [{ name: 'init', extensions: ['json'] }]
            })
            .then((result) => {
              if (result.canceled) return
              setCurrentWorkSpace(result.filePaths[0])
            })
            .catch((err) => {
              console.log(err)
            })
        }
      },
      {
        label: '新建工程',
        role: 'help',
        click: function () {
          mainWindow.webContents.send('newProject')
        }
      },
      {
        label: '另存为',
        role: 'help',
        click: function () {
          let result = dialog.showSaveDialogSync({
            title: '另存为',
            securityScopedBookmarks: true,
            filters: [{ name: 'json', extensions: ['json'] }]
          })
          if (result) {
            saveConfigAs(result)
          }
        }
      }
    ]
  },
  {
    label: '工具',
    submenu: [
      {
        label: '导入字库',
        role: 'help',
        click: importFont
      },
      {
        label: '导入图片',
        role: 'help',
        click: importImage
      },
      {
        label: '导入音频',
        role: 'help',
        click: importAudio
      }
    ]
  },
  {
    label: '帮助',
    submenu: [
      {
        label: '指令集',
        role: 'help',
        click: function () {
          shell.openExternal('http://www.tianrenyun.cn/')
        }
      },
      {
        label: '资料中心',
        role: 'help',
        click: function () {
          shell.openExternal('http://www.tianrenyun.cn/')
        }
      }
    ]
  },
  {
    label: '关于',
    submenu: [
      {
        label: '关于本软件',
        role: 'help',
        click: function () {
          dialog.showMessageBox({ message: '本软件主要是通过拖拽的形式生成Lua脚本。' })
        }
      }
    ]
  }
]

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      allowRunningInsecureContent: true
    }
  })
  //默认打开最大化
  mainWindow.maximize()
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    let recentDir = store.get('currentworkconfig')
    store.set('currentworkconfig', '')
    setCurrentWorkSpace(recentDir)
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  const mainMenu = Menu.buildFromTemplate(Menus)
  Menu.setApplicationMenu(mainMenu)

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.webContents.openDevTools({ mode: 'undocked' })
    log.info('Main process ready')
  }
}

// 监听未捕获的异常
process.on('uncaughtException', (error) => {
  log.error('Uncaught Exception:', error)
  // 在这里可以添加自定义的错误处理逻辑
})

// 监听未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
  log.error('Unhandled Rejection at:', promise, 'reason:', reason)
  // 在这里添加错误处理逻辑
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  // 检查命令行参数是否有项目文件路径
  const projectFilePath = process.argv.find((arg) => arg.endsWith(initConfigName))
  if (projectFilePath) {
    // 加载传入的项目文件
    setCurrentWorkSpace(projectFilePath)
  } else {
    // 打开最近的项目
    let recentDir = store.get('currentworkconfig')
    setCurrentWorkSpace(recentDir)
  }

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

ipcMain.on('preview', function () {
  exportLua().then(() => {
    console.log('preview')
    cmd.run(`cd ${currentworkspace}`)
    // console.log('currentworkspace', currentworkspace)
    // cmd.run(`${simulator} ${currentworkspace}`)
    cmd.run(`cd ${currentworkspace} && start "调试信息" cmd /C ${simulator} ${currentworkspace}`)
  })
})
// 处理导出项目的请求
ipcMain.handle('exportProject', async (event, exportPath) => {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showErrorBox('缺失配置', '请先打开配置')
    return
  }

  // 调用导出 Lua 文件的函数
  await exportLua()

  // 创建目标目录
  const targetDir = path.join(exportPath, 'screen7')

  try {
    // 检查并删除已存在的screen7文件夹
    if (fs.existsSync(targetDir)) {
      await fs.promises.rm(targetDir, { recursive: true, force: true })
      console.log('已删除旧版screen7文件夹')
    }
    // 确保目标目录存在
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true })
    }

    // 复制LUA文件夹（完整复制）
    const luaSource = path.join(currentworkspace, 'LUA')
    const luaTarget = path.join(targetDir, 'LUA')
    await fs.promises.cp(luaSource, luaTarget, { recursive: true })

    // 复制HOMEI文件夹（排除.txt文件）
    const homeiSource = path.join(currentworkspace, 'HOMEI')
    const homeiTarget = path.join(targetDir, 'HOMEI')

    // 创建目标目录
    await fs.promises.mkdir(homeiTarget, { recursive: true })

    // 读取源目录内容并过滤
    const entries = await fs.promises.readdir(homeiSource, { withFileTypes: true })

    for (const entry of entries) {
      const srcPath = path.join(homeiSource, entry.name)
      const destPath = path.join(homeiTarget, entry.name)

      // 如果是目录则递归复制
      if (entry.isDirectory()) {
        await fs.promises.cp(srcPath, destPath, { recursive: true })
      }
      // 如果是文件且不是.txt文件则复制
      else if (!entry.name.toLowerCase().endsWith('.txt')) {
        await fs.promises.copyFile(srcPath, destPath)
      }
      // 否则跳过.txt文件
    }

    return 'success'
  } catch (error) {
    console.error('导出失败:', error)
    throw error
  }
})

ipcMain.handle('showOpenDialog', async (event, options) => {
  return await dialog.showOpenDialog(options)
})

ipcMain.handle('get-serial-ports', async () => {
  try {
    const ports = await SerialPort.list()
    return ports
  } catch (error) {
    console.error('获取串口列表失败:', error)
    return []
  }
})

ipcMain.handle('getStoreValue', (key) => {
  return store.get(key)
})

ipcMain.handle('saveStoreValue', (key, value) => {
  return store.set(key, value)
})

ipcMain.handle('saveJson', (value) => {
  saveConfigToFile(value)
})

ipcMain.handle('getCurrentWorkSpace', () => {
  return currentworkspace
})
ipcMain.handle('getCurrentWorkConfig', () => {
  fs.readFile(currentworkconfig, 'utf-8', (err, data) => {
    if (err) {
      console.log(err)
      return
    }
    return data
  })
})

ipcMain.on('newWorkConfig', () => {
  let result = dialog.showSaveDialogSync({
    title: '新建',
    securityScopedBookmarks: true,
    filters: [{ name: 'json', extensions: ['json'] }]
  })
  if (result) {
    currentworkspace = path.dirname(result)
    currentworkconfig = result
    mainWindow.webContents.send('openSettings')
  }
})
ipcMain.on('openUserPath', (event) => {
  let result = dialog.showOpenDialogSync({
    title: '新建工程目录',
    securityScopedBookmarks: true,
    properties: ['openDirectory', 'createDirectory', 'promptToCreate']
  })
  if (result === undefined) {
    event.returnValue = ''
  } else {
    event.returnValue = result[0]
  }
})
ipcMain.on('initSettings', (_event, settings) => {
  if (settings.projectPath == '') {
    dialog.showErrorBox('错误提示', '创建工程失败，请选择工程目录！')
  } else if (fs.readdirSync(settings.projectPath).length > 0) {
    dialog.showErrorBox('错误提示', '创建工程失败，目录非空！')
  } else {
    initCurrentWorkSpace(settings)
  }
})

ipcMain.on('openProject', () => {
  dialog
    .showOpenDialog({
      properties: ['openFile'],
      title: '选择工程文件',
      filters: [{ name: 'init', extensions: ['json'] }]
    })
    .then((result) => {
      if (result.canceled) return
      setCurrentWorkSpace(result.filePaths[0])
    })
    .catch((err) => {
      console.log(err)
    })
})

const initJson = {
  main: { name: 'main', type: 'code', lang: 'lua', content: '', readOnly: false },
  pages: [
    {
      type: 'Page',
      lastUserId: 20000,
      wageList: [],
      options: {
        id: 0,
        name: 'main_ui',
        rgb: '#808080',
        opa: 255,
        bgType: 1,
        img: '',
        code: `function on_systick_ui() \r\nend \r\n\r\nfunction on_control_notify(objId, type, user_data, value) \r\nend\r\n`
      }
    }
  ],
  settings: {
    width: 1024,
    height: 600,
    screenOrientation: 0,
    serialPort: 2,
    baudRate: 0,
    scale: 100
  }
}
//新建工程初始化
function initCurrentWorkSpace(settings) {
  let filePath = path.join(settings.projectPath, initConfigName)
  currentworkconfig = filePath
  currentworkspace = filePath.replace('init.json', '')
  fs.access(settings.projectPath, fs.constants.F_OK, (err) => {
    if (err) {
      fs.mkdir(settings.projectPath, { recursive: true }, (err) => {
        if (err) {
          console.log('project mkdir fail', err)
          return
        }
        console.log('project mkdir success')
      })
    }
  })
  // Buffer.from(JSON.stringify(initJson))
  store.set('currentworkconfig', filePath)
  store.set('currentworkspace', currentworkspace)
  initJson.settings.projectPath = currentworkspace
  initJson.settings.width = settings.width
  initJson.settings.height = settings.height
  initJson.settings.screenOrientation = settings.screenOrientation
  initJson.settings.serialPort = settings.serialPort || '1' // 默认使用COM1
  initJson.settings.baudRate = settings.baudRate
  initJson.settings.scale = settings.scale
  store.set(currentworkspace, initJson)

  fs.mkdir(currentworkspace + '/LUA', { recursive: true }, (err) => {
    if (err) {
      dialog.showErrorBox('错误提示', '创建文件夹失败，请重试')
      return
    }
    fs.writeFileSync(
      currentworkspace + '/LUA/main_ui.lua',
      formatTextPlus(
        InitPageGenerator('parentId', '', '0x808080', '', '') +
          `function on_systick_ui() \r\nend \r\n\r\nfunction on_control_notify(objId, type, user_data, value) \r\nend`
      )
    )
  })

  fs.mkdir(currentworkspace + '/HOMEI', { recursive: true }, (err) => {
    if (err) {
      console.log('project mkdir fail', err)
      return
    }
    fs.copyFile(ChineseSimplified, currentworkspace + '/HOMEI/font_1.ttf', () => {})
    console.log('project mkdir success')
    fs.writeFileSync(filePath, JSON.stringify(initJson).toString())
    mainWindow.webContents.send('setCurrentWorkConfig', currentworkconfig)
  })
}
function isValidPageConfig(config) {
  try {
    // Basic structure checks
    if (!config || typeof config !== 'object') return false

    // Check required fields for a page config
    if (!config.pages || !Array.isArray(config.pages)) return false
    if (!config.settings || typeof config.settings !== 'object') return false

    // Check at least one page exists and has required fields
    if (config.pages.length === 0) return false
    const firstPage = config.pages[0]
    if (!firstPage.options || typeof firstPage.options !== 'object') return false

    return true
  } catch (e) {
    return false
  }
}

function setCurrentWorkSpace(filePath) {
  if (!filePath) return
  if (filePath === store.get('currentworkconfig')) return

  let projectPath = filePath.replace(initConfigName, '')

  if (!fs.existsSync(filePath)) {
    // Handle case when directory doesn't have config file
    dialog.showErrorBox('错误', '配置文件不存在')
    return
  } else {
    try {
      // Read and parse the file
      const fileContent = fs.readFileSync(filePath, 'utf-8')
      const config = JSON.parse(fileContent)

      // Validate the config
      if (!isValidPageConfig(config)) {
        dialog.showErrorBox('错误', '文件格式错误(非项目文件)')
        return
      }

      currentworkconfig = path.join(projectPath, initConfigName)
      currentworkspace = projectPath
      store.set('currentworkconfig', currentworkconfig)
      store.set('currentworkspace', currentworkspace)
      mainWindow.webContents.send('setCurrentWorkConfig', currentworkconfig)
    } catch (error) {
      console.error('Error reading/parsing config file:', error)
      dialog.showErrorBox('错误', '配置文件读取失败或格式错误')
    }
  }
}

function saveConfigToFile(value) {
  fs.writeFileSync(currentworkconfig, JSON.stringify(value))
}

function saveConfigAs(filePath) {
  fs.writeFileSync(filePath, JSON.stringify(store.get('currentworkconfig')))
}

ipcMain.on('loadConfig', (event, filePath) => {
  if (fs.existsSync(filePath)) {
    console.log('parms:', filePath)
    // console.log('xxxxx:', JSON.parse(fs.readFileSync(filePath)))
    event.returnValue = JSON.parse(fs.readFileSync(filePath))
  } else {
    event.returnValue = initJson
  }
})
// eslint-disable-next-line no-unused-vars
async function exportLua() {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showErrorBox('缺失配置', '请先打开配置')
    return
  }
  console.log(currentworkspace)
  if (fs.existsSync(currentworkspace + '/LUA')) {
    fs.readdirSync(currentworkspace + '/LUA').forEach((file) => {
      if (file != 'main.lua' && file != 'main_ui.lua') {
        const curPath = path.join(currentworkspace + '/LUA', file)
        // 如果是文件，直接删除
        fs.unlinkSync(curPath)
      }
    })
  }
  fs.mkdir(currentworkspace + '/LUA', { recursive: true }, (err) => {
    if (err) {
      dialog.showErrorBox('错误提示', '创建文件夹失败，请重试')
    }
  })
  let exportConfig = JSON.parse(fs.readFileSync(currentworkconfig))

  configTextToFile(exportConfig)

  let pages = exportConfig.pages
  for (let page of pages) {
    store.set('notifyUiCode', '')
    let pageName = currentworkspace + '/LUA/' + page.options.name + '.lua'
    fs.writeFileSync(pageName, '')
    // const writeStream = fs.createWriteStream(pageName)

    // if (page.options.bgType == 2 && page.options.img == '') {
    //   dialog.showErrorBox('错误提示', '背景图片未设置，请设置背景图片')
    //   return
    // }

    let initpageData = InitPageGenerator(
      'parentId',
      page.options.bgType,
      page.options.rgb,
      page.options.opa,
      page.options.img
    )
    // writeStream.write(formatText(initpageData))
    appendFileSync(pageName, formatTextPlus(initpageData))
    if (page.options.on_control_notify) {
      // console.log('on_control_notify')
      // writeStream.write(formatText(OnControlNotifyGenerator(page.options.on_control_notify)))
      appendFileSync(
        pageName,
        formatTextPlus(OnControlNotifyGenerator(page.options.on_control_notify))
      )
    }
    if (page.options.on_systick_ui) {
      // console.log('on_systick_ui')
      // writeStream.write(formatText(OnSystickUiGenerator(page.options.on_systick_ui)))
      appendFileSync(pageName, formatTextPlus(OnSystickUiGenerator(page.options.on_systick_ui)))
    }

    let widgetList = page.widgetList
    // recursionExportLua(writeStream, widgetList, 'parentId')
    recursionExportLua(pageName, widgetList, 'parentId')
    let notifyUiCode = store.get('notifyUiCode')
    // console.log('notifyUiCode', notifyUiCode)
    appendFileSync(pageName, formatTextPlus(OnControlNotifyUiGenerator(notifyUiCode)))
    appendFileSync(pageName, formatTextPlus(page.options.code))
    // writeStream.write(formatText(OnControlNotifyUiGenerator(notifyUiCode)))
    // writeStream.write(formatText(page.options.code))
    // writeStream.close()
    // // writeStream.end()
    // writeStream.on('finish', () => {
    //   console.log(pageName, 'write finished')
    // })
    store.set('notifyUiCode', '')
  }
  if (exportConfig.subLuaList) {
    let subLuaList = exportConfig.subLuaList
    for (let subLua of subLuaList) {
      appendFileSync(currentworkspace + '/LUA/' + subLua.name + '.lua', formatTextPlus(subLua.code))
    }
  }
}

function configTextToFile(exportConfig) {
  let settings = exportConfig.settings

  // 处理串口号 - 确保是数字且在1-256范围内
  let serialPortNumber = 1 // 默认值
  if (settings.serialPort) {
    // 直接转换为数字
    serialPortNumber = parseInt(settings.serialPort, 10) || 1
    // 确保在1-256范围内
    serialPortNumber = Math.max(1, Math.min(256, serialPortNumber))
  }

  exportConfig.main.content += `\r\ninit_modbus(` + serialPortNumber + `,` + settings.baudRate + `)`
  exportConfig.main.content +=
    `\r\nset_screen_size(` +
    settings.width +
    `,` +
    settings.height +
    `,` +
    settings.screenOrientation +
    `)`
  exportConfig.main.content += `\r\nset_screen_scale(` + settings.scale + `)`

  fs.writeFileSync(currentworkspace + '/LUA/main.lua', formatTextPlus(exportConfig.main.content))

  //写语言
  let languages = settings.languages
  if (languages) {
    let languagesLuaText = 'set_language_map_font(1,1)\r\n'
    languages.forEach((langu, index) => {
      languagesLuaText +=
        `set_language_map_font(${index + 2}, ` +
        langu.value.replace('.ttf', '').replace('font_', '') +
        `)\r\n`
    })
    languagesLuaText += 'set_language(get_language())'
    fs.writeFileSync(currentworkspace + '/LUA/main_language.lua', formatTextPlus(languagesLuaText))
  }
}

function addWidgetLuaText(pageName, content) {
  if (pageName != '' && pageName != null) {
    appendFileSync(pageName, content)
  } else {
    store.set('slidePageLuaText', store.get('slidePageLuaText') + content)
  }
}

function recursionExportLua(pageName, widgetList, parentId) {
  for (let widget of widgetList) {
    switch (widget.type) {
      case 'button':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            ButtonGenerator(
              widget.options.name,
              parentId,
              widget.options.width,
              widget.options.height,
              widget.options.color,
              widget.options.colorLine,
              widget.options.widthLine,
              widget.options.opa,
              widget.options.radius,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.event1,
              widget.options.event2,
              widget.options.userId,
              widget.options.bgType,
              widget.options.pngId,
              widget.options.pngAlign,
              widget.options.isTitle,
              widget.options.titleText,
              widget.options.fontSize,
              widget.options.fontColor,
              widget.options.fontType,
              widget.options.titleAlign,
              widget.options.hidden
            )
          )
        )
        if (
          widget.options.event1 != '' &&
          widget.options.event1Code != '' &&
          widget.options.event1Code != undefined
        ) {
          let notifyUiCode = store.get('notifyUiCode')
          notifyUiCode =
            notifyUiCode +
            `\r\nif user_data==` +
            widget.options.userId +
            `and type==` +
            widget.options.event1 +
            ` then \r\n` +
            widget.options.event1Code +
            `\r\n end`
          store.set('notifyUiCode', notifyUiCode)
        }

        if (
          widget.options.event2 != '' &&
          widget.options.event2Code != '' &&
          widget.options.event2Code != undefined
        ) {
          let notifyUiCode = store.get('notifyUiCode')
          notifyUiCode =
            notifyUiCode +
            `\r\nif user_data==` +
            widget.options.userId +
            `and type==` +
            widget.options.event2 +
            ` then \r\n` +
            widget.options.event2Code +
            `\r\n end`
          store.set('notifyUiCode', notifyUiCode)
        }
        recursionExportLua(pageName, widget.widgetList, widget.options.name)
        break
      case 'picture':
        if (widget.options.pngId == '') {
          log.error('图片ID未设置，请先选择图片: ', widget.options.name)
        } else {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              ImageGenerator(
                widget.options.name,
                parentId,
                widget.options.pngId,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.hidden
              )
            )
          )
        }
        break
      case 'qrCode':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            QrCodeGenerator(
              widget.options.name,
              parentId,
              widget.options.width,
              widget.options.strLabel,
              widget.options.colorBack,
              widget.options.colorQr,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.hidden
            )
          )
        )
        break
      case 'staticText':
        if (widget.options.isSetSize) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              BorderLabelGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.strLabel,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.staticTextAlign,
                widget.options.x,
                widget.options.y,
                widget.options.hidden
              )
            )
          )
        } else {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              LabelGenerator(
                widget.options.name,
                parentId,
                widget.options.strLabel,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.hidden
              )
            )
          )
        }
        break
      case 'number':
        if (widget.options.type == 'modbus' && widget.options.isInput == 0) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              ModbusDataLabelGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.modbusAddress,
                widget.options.dotNum,
                widget.options.isNagetive,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.isNeedHideDot,
                widget.options.hidden
              )
            )
          )
        } else if (widget.options.type == 'userData' && widget.options.isInput == 0) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              UserDataLableGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.userDataId,
                widget.options.userDataAddress,
                widget.options.dotNum,
                widget.options.isNagetive,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.isNeedHideDot,
                widget.options.hidden
              )
            )
          )
        } else if (widget.options.type == 'modbus' && widget.options.isInput == 1) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              ModbusDataInputGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.title,
                widget.options.modbusAddress,
                widget.options.dotNum,
                widget.options.isNagetive,
                widget.options.min,
                widget.options.max,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.isNeedHideDot,
                widget.options.hidden,
                widget.options.userId
              )
            )
          )
          if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
            let notifyUiCode = store.get('notifyUiCode')
            notifyUiCode =
              notifyUiCode +
              `\r\nif user_data==` +
              widget.options.userId +
              ` then \r\n` +
              widget.options.eventCode +
              `\r\n end`
            store.set('notifyUiCode', notifyUiCode)
          }
        } else if (widget.options.type == 'userData' && widget.options.isInput == 1) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              UserDataInputGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.title,
                widget.options.userDataId,
                widget.options.userDataAddress,
                widget.options.dotNum,
                widget.options.isNagetive,
                widget.options.min,
                widget.options.max,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.isNeedHideDot,
                widget.options.hidden,
                widget.options.userId
              )
            )
          )
          if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
            let notifyUiCode = store.get('notifyUiCode')
            notifyUiCode =
              notifyUiCode +
              `\r\nif user_data==` +
              widget.options.userId +
              ` then \r\n` +
              widget.options.eventCode +
              `\r\n end`
            store.set('notifyUiCode', notifyUiCode)
          }
        }
        break
      case 'text':
        if (widget.options.type == 'modbus' && widget.options.isInput == 0) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              ModbusStringLabelGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.modbusAddress,
                widget.options.modbusAddress.length,
                widget.options.highFirst,
                widget.options.language,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.staticTextAlign,
                widget.options.hidden
              )
            )
          )
        } else if (widget.options.type == 'userData' && widget.options.isInput == 0) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              UserDataStringLabelGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.userDataId,
                widget.options.userDataAddress,
                widget.options.userAddressLen,
                widget.options.highFirst,
                widget.options.language,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.staticTextAlign,
                widget.options.hidden
              )
            )
          )
        } else if (widget.options.type == 'modbus' && widget.options.isInput == 1) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              ModbusStringInputGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.title,
                widget.options.modbusAddress,
                widget.options.len,
                widget.options.highFirst,
                widget.options.language,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.staticTextAlign,
                widget.options.hidden,
                widget.options.needFresh,
                widget.options.userId
              )
            )
          )
          if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
            let notifyUiCode = store.get('notifyUiCode')
            notifyUiCode =
              notifyUiCode +
              `\r\nif user_data==` +
              widget.options.userId +
              ` then \r\n` +
              widget.options.eventCode +
              `\r\n end`
            store.set('notifyUiCode', notifyUiCode)
          }
        } else if (widget.options.type == 'userData' && widget.options.isInput == 1) {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              UserDataStringInputGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.colorLine,
                widget.options.widthLine,
                widget.options.opa,
                widget.options.radius,
                widget.options.isCover,
                widget.options.title,
                widget.options.userDataId,
                widget.options.userDataAddress,
                widget.options.userAddressLen,
                widget.options.highFirst,
                widget.options.language,
                widget.options.fontSize,
                widget.options.fontColor,
                widget.options.fontType,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.staticTextAlign,
                widget.options.hidden,
                widget.options.needFresh,
                widget.options.userId
              )
            )
          )
          if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
            let notifyUiCode = store.get('notifyUiCode')
            notifyUiCode =
              notifyUiCode +
              `\r\nif user_data==` +
              widget.options.userId +
              ` then \r\n` +
              widget.options.eventCode +
              `\r\n end`
            store.set('notifyUiCode', notifyUiCode)
          }
        }
        break
      case 'progress':
        // if (widget.options.type == 'modbus') {
        //   addWidgetLuaText(
        //     pageName,
        //     formatTextPlus(
        //       BarGenerator(
        //         widget.options.name,
        //         parentId,
        //         widget.options.width,
        //         widget.options.height,
        //         widget.options.minrange,
        //         widget.options.maxrange,
        //         widget.options.colorSelect,
        //         widget.options.colorBack,
        //         widget.options.baseId,
        //         widget.options.align,
        //         widget.options.x,
        //         widget.options.y,
        //         widget.options.hidden,
        //         'modbus',
        //         widget.options.modbusAddress,
        //         undefined,
        //         undefined
        //       )
        //     )
        //   )
        // }
        // if (widget.options.type == 'userData')
        {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              BarGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.minrange,
                widget.options.maxrange,
                widget.options.colorSelect,
                widget.options.colorBack,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.hidden
                // 'userData',
                // undefined,
                // widget.options.userDataId,
                // widget.options.userDataAddress
              )
            )
          )
        }
        break
      case 'switch':
        // if (widget.options.type == 'modbus') {
        //   addWidgetLuaText(
        //     pageName,
        //     formatTextPlus(
        //       SwitchGenerator(
        //         widget.options.name,
        //         parentId,
        //         widget.options.width,
        //         widget.options.height,
        //         widget.options.fontSize,
        //         widget.options.colorSelectLeft,
        //         widget.options.colorSelectRight,
        //         widget.options.colorSelectLeftFont,
        //         widget.options.colorSelectRightFont,
        //         widget.options.selectLeftText,
        //         widget.options.selectRightText,
        //         widget.options.userId,
        //         widget.options.baseId,
        //         widget.options.align,
        //         widget.options.x,
        //         widget.options.y,
        //         widget.options.colorSwitch,
        //         widget.options.hidden,
        //         'modbus',
        //         widget.options.modbusAddress,
        //         undefined,
        //         undefined,
        //         widget.options.bit
        //       )
        //     )
        //   )
        // } else if (widget.options.type == 'userData') {
        //   addWidgetLuaText(
        //     pageName,
        //     formatTextPlus(
        //       SwitchGenerator(
        //         widget.options.name,
        //         parentId,
        //         widget.options.width,
        //         widget.options.height,
        //         widget.options.fontSize,
        //         widget.options.colorSelectLeft,
        //         widget.options.colorSelectRight,
        //         widget.options.colorSelectLeftFont,
        //         widget.options.colorSelectRightFont,
        //         widget.options.selectLeftText,
        //         widget.options.selectRightText,
        //         widget.options.userId,
        //         widget.options.baseId,
        //         widget.options.align,
        //         widget.options.x,
        //         widget.options.y,
        //         widget.options.colorSwitch,
        //         widget.options.hidden,
        //         'userData',
        //         undefined,
        //         widget.options.userDataId,
        //         widget.options.userDataAddress,
        //         widget.options.bit
        //       )
        //     )
        //   )
        // }
        {
          // No address mapping
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              SwitchGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.fontSize,
                widget.options.colorSelectLeft,
                widget.options.colorSelectRight,
                widget.options.colorSelectLeftFont,
                widget.options.colorSelectRightFont,
                widget.options.selectLeftText,
                widget.options.selectRightText,
                widget.options.userId,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.colorSwitch,
                widget.options.hidden
                // No type specified means no address mapping
              )
            )
          )
        }
        if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
          let notifyUiCode = store.get('notifyUiCode')
          notifyUiCode =
            notifyUiCode +
            `\r\nif user_data==` +
            widget.options.userId +
            ` then \r\n` +
            widget.options.eventCode +
            `\r\n end`
          store.set('notifyUiCode', notifyUiCode)
        }
        break
      case 'led':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            LedGenerator(
              widget.options.name,
              parentId,
              widget.options.width,
              widget.options.height,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.type,
              widget.options.modbusAddress,
              widget.options.userDataId,
              widget.options.userDataAddress,
              widget.options.bit,
              widget.options.colorOn,
              widget.options.colorOff,
              widget.options.hidden
            )
          )
        )
        break
      case 'select':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            ComboboxGenerator(
              widget.options.name,
              parentId,
              widget.options.width,
              widget.options.height,
              widget.options.colorBack,
              widget.options.radius,
              widget.options.fontSize,
              widget.options.fontColor,
              widget.options.fontType,
              widget.options.widthLine,
              widget.options.color,
              widget.options.downWidth,
              widget.options.downHeight,
              widget.options.downColor,
              widget.options.downLine,
              widget.options.downLineColor,
              widget.options.downFontSize,
              widget.options.downFontColor,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.userId,
              widget.options.optionItems,
              widget.options.value,
              widget.options.hidden
            )
          )
        )
        if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
          let notifyUiCode = store.get('notifyUiCode')
          notifyUiCode =
            notifyUiCode +
            `\r\nif user_data==` +
            widget.options.userId +
            ` then \r\n` +
            widget.options.eventCode +
            `\r\n end`
          store.set('notifyUiCode', notifyUiCode)
        }
        break
      case 'gif':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            GifGenerator(
              widget.options.name,
              parentId,
              widget.options.pngStartId,
              widget.options.pngSize,
              widget.options.timer,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.hidden
            )
          )
        )
        break
      case 'gif2':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            Gif2Generator(
              widget.options.name,
              parentId,
              widget.options.gifId,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.hidden
            )
          )
        )
        break
      case 'audio':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            SoundGenerator(
              widget.options.soundId,
              widget.options.defaultCnt,
              widget.options.enablePage,
              widget.options.voice
            )
          )
        )
        break
      case 'module':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            ModuleGenerator(
              widget.options.name,
              parentId,
              widget.options.width,
              widget.options.height,
              widget.options.color,
              widget.options.colorLine,
              widget.options.widthLine,
              widget.options.opa,
              widget.options.radius,
              widget.options.isCover,
              widget.options.scrollType,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.hidden,
              widget.options.scrollWidth,
              widget.options.scrollHeight
            )
          )
        )
        recursionExportLua(pageName, widget.widgetList, widget.options.name)
        break

      case 'slidePage':
        var arr = []
        // console.log('a ', widget.widgetList)
        // console.log('x ', widget.widgetList[0])
        widget.widgetList.forEach((page) => {
          // console.log('y ', page, index)
          store.set('slidePageLuaText', '')
          recursionExportLua(null, page.widgetList, widget.options.name)
          arr.push(store.get('slidePageLuaText'))
          console.log(store.get('slidePageLuaText'))
        })

        addWidgetLuaText(
          pageName,
          formatTextPlus(
            SlidePageGenerator(
              widget.options.name,
              parentId,
              widget.options.width,
              widget.options.height,
              widget.options.color,
              widget.options.colorLine,
              widget.options.widthLine,
              widget.options.opa,
              widget.options.radius,
              widget.options.isCover,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.hidden,
              widget.options.slideButtonLeft,
              widget.options.slideButtonRight,
              widget.options.slideButtonWidth,
              widget.options.slideButtonHeight,
              arr
            )
          )
        )
        break
      case 'table':
        addWidgetLuaText(
          pageName,
          formatTextPlus(
            TableGenerator(
              widget.options.name,
              parentId,
              widget.options.width,
              widget.options.height,
              widget.options.baseId,
              widget.options.align,
              widget.options.x,
              widget.options.y,
              widget.options.hidden,
              widget.options.rows,
              widget.options.cols,
              widget.options.widthLine,
              widget.options.color,
              widget.options.opa,
              1,
              0,
              0
            )
          )
        )
        break
    }
  }
  for (let widget of widgetList) {
    switch (widget.type) {
      case 'slider':
        if (widget.options.type == 'modbus') {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              SliderGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.step,
                widget.options.minrange,
                widget.options.maxrange,
                widget.options.colorSelect,
                widget.options.colorBack,
                widget.options.colorKnob,
                widget.options.userId,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.pos,
                widget.options.staticText,
                widget.options.hidden,
                'modbus',
                widget.options.modbusAddress,
                undefined,
                undefined
              )
            )
          )
          if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
            let notifyUiCode = store.get('notifyUiCode')
            notifyUiCode =
              notifyUiCode +
              `\r\nif user_data==` +
              widget.options.userId +
              ` then \r\n` +
              widget.options.eventCode +
              `\r\n end`
            store.set('notifyUiCode', notifyUiCode)
          }
        }
        if (widget.options.type == 'userData') {
          addWidgetLuaText(
            pageName,
            formatTextPlus(
              SliderGenerator(
                widget.options.name,
                parentId,
                widget.options.width,
                widget.options.height,
                widget.options.step,
                widget.options.minrange,
                widget.options.maxrange,
                widget.options.colorSelect,
                widget.options.colorBack,
                widget.options.colorKnob,
                widget.options.userId,
                widget.options.baseId,
                widget.options.align,
                widget.options.x,
                widget.options.y,
                widget.options.pos,
                widget.options.staticText,
                widget.options.hidden,
                'userData',
                undefined,
                widget.options.userDataId,
                widget.options.userDataAddress
              )
            )
          )
          if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
            let notifyUiCode = store.get('notifyUiCode')
            notifyUiCode =
              notifyUiCode +
              `\r\nif user_data==` +
              widget.options.userId +
              ` then \r\n` +
              widget.options.eventCode +
              `\r\n end`
            store.set('notifyUiCode', notifyUiCode)
          }
        }
        // } else {
        //   addWidgetLuaText(
        //     pageName,
        //     formatTextPlus(
        //       SliderGenerator(
        //         widget.options.name,
        //         parentId,
        //         widget.options.width,
        //         widget.options.height,
        //         widget.options.step,
        //         widget.options.minrange,
        //         widget.options.maxrange,
        //         widget.options.colorSelect,
        //         widget.options.colorBack,
        //         widget.options.colorKnob,
        //         widget.options.userId,
        //         widget.options.baseId,
        //         widget.options.align,
        //         widget.options.x,
        //         widget.options.y,
        //         widget.options.pos,
        //         widget.options.staticText,
        //         widget.options.hidden
        //       )
        //     )
        //   )
        //   if (widget.options.eventCode != '' && widget.options.eventCode != undefined) {
        //     let notifyUiCode = store.get('notifyUiCode')
        //     notifyUiCode =
        //       notifyUiCode +
        //       `\r\nif user_data==` +
        //       widget.options.userId +
        //       ` then \r\n` +
        //       widget.options.eventCode +
        //       `\r\n end`
        //     store.set('notifyUiCode', notifyUiCode)
        //   }
        // }
        break
    }
  }
}

async function batchCopy(filePaths, type) {
  const targetDir = currentworkspace + '/HOMEI'
  // 读取目标文件夹中的所有文件
  const files = await fs.promises.readdir(targetDir)

  if (type == 'font') {
    // 过滤 字库并映射到文件名中的计数部分
    const fontFiles = files
      .filter((file) => path.extname(file).toLowerCase() === '.ttf')
      .map((file) => file.match(/^font_(\d+).ttf$/)) // 正则匹配并提取数字部分
      .filter(Boolean) // 过滤掉不匹配的项
      .map((match) => parseInt(match[1], 10)) // 转换为数字

    // 计算最大计数
    let maxCountFont = Math.max(...fontFiles, 0) // 是为了下一个文件名使用

    for (let filePath of filePaths) {
      // console.log(filePath)
      fs.copyFileSync(
        filePath,
        currentworkspace + '/HOMEI/' + 'font_' + (maxCountFont + 1) + '.ttf',
        0
      )
      maxCountFont++
    }
  } else if (type == 'img') {
    // 过滤 PNG 图片并映射到文件名中的计数部分
    const pngFiles = files
      .filter((file) => path.extname(file).toLowerCase() === '.png')
      .map((file) => file.match(/^P(\d+).png$/)) // 正则匹配并提取数字部分
      .filter(Boolean) // 过滤掉不匹配的项
      .map((match) => parseInt(match[1], 10)) // 转换为数字

    // 计算最大计数
    let maxCountPng = Math.max(...pngFiles, 0) // 是为了下一个文件名使用

    for (let filePath of filePaths) {
      // console.log(filePath)
      fs.copyFileSync(filePath, currentworkspace + '/HOMEI/' + 'P' + (maxCountPng + 1) + '.png', 0)
      maxCountPng++
    }
  } else if (type == 'gif') {
    // 过滤 PNG 图片并映射到文件名中的计数部分
    const gifFiles = files
      .filter((file) => path.extname(file).toLowerCase() === '.gif')
      .map((file) => file.match(/^G(\d+).gif$/)) // 正则匹配并提取数字部分
      .filter(Boolean) // 过滤掉不匹配的项
      .map((match) => parseInt(match[1], 10)) // 转换为数字

    // 计算最大计数
    let maxCountPng = Math.max(...gifFiles, 0) // 是为了下一个文件名使用

    for (let filePath of filePaths) {
      // console.log(filePath)
      fs.copyFileSync(filePath, currentworkspace + '/HOMEI/' + 'G' + (maxCountPng + 1) + '.gif', 0)
      maxCountPng++
    }
  } else if (type == 'audio') {
    const audioFiles = files
      .filter((file) => path.extname(file).toLowerCase() === '.wav')
      .map((file) => file.match(/^(\d+).wav$/)) // 正则匹配并提取数字部分
      .filter(Boolean) // 过滤掉不匹配的项
      .map((match) => parseInt(match[1], 10)) // 转换为数字

    // 计算最大计数
    let maxCountAudio = Math.max(...audioFiles, 0) // 是为了下一个文件名使用

    for (let filePath of filePaths) {
      // console.log(filePath)
      fs.copyFileSync(filePath, currentworkspace + '/HOMEI/' + (maxCountAudio + 1) + '.wav', 0)
      maxCountAudio++
    }
  } else if (type == 'video') {
    const videoFiles = files
      .filter((file) => path.extname(file).toLowerCase() === '.video')
      .map((file) => file.match(/^(\d+).video$/)) // 正则匹配并提取数字部分
      .filter(Boolean) // 过滤掉不匹配的项
      .map((match) => parseInt(match[1], 10)) // 转换为数字

    // 计算最大计数
    let maxCountVideo = Math.max(...videoFiles, 0) // 是为了下一个文件名使用

    for (let filePath of filePaths) {
      // console.log(filePath)
      fs.copyFileSync(
        filePath,
        currentworkspace + '/HOMEI/' + 'P' + (maxCountVideo + 1) + '.png',
        0
      )
      maxCountVideo++
    }
  }
}

function formatTextPlus(text) {
  console.log('need format deal: ', text)
  return formatText(text)
}

ipcMain.on('exportLua', (event) => {
  exportLua()
  event.returnValue = 'success'
})

ipcMain.on('downLoad', (event) => {
  // console.log('下载')
  exportLua()
  dialog
    .showOpenDialog({
      title: '请选择下载目录',
      properties: ['openDirectory', 'createDirectory']
    })
    .then((result) => {
      if (result.canceled) return
      console.log(result)
      console.log(configJson)
      let projectName = 'screen7'
      fs.open(configJson, 'r', (err) => {
        if (err) {
          if (err.code === 'ENOENT') {
            console.error(configJson, 'does not exist')
          }
        }
        let content = JSON.parse(fs.readFileSync(configJson, { encoding: 'utf-8' }))
        projectName = content.downLoadDirectory

        let targetDir = result.filePaths[0] + '/' + projectName
        fs.rm(targetDir, { recursive: true, force: true }, (err) => {
          if (err) {
            console.error(err)
          } else {
            console.log(targetDir, 'Directory deleted successfully')

            fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
              if (
                file.endsWith('.ttf') ||
                file.endsWith('.png') ||
                file.endsWith('.gif') ||
                file.endsWith('.wav') ||
                file.endsWith('.video')
              ) {
                fs.cp(currentworkspace + '/HOMEI/' + file, targetDir + '/HOMEI/' + file, (err) => {
                  if (err) {
                    console.error(err)
                  } else {
                    console.log(
                      file,
                      ' is copied from ',
                      currentworkspace + 'HOMEI',
                      ' to ',
                      targetDir + '/HOMEI/'
                    )
                  }
                })
              }
            })
          }

          fs.cp(currentworkspace + '/LUA/', targetDir + '/LUA/', { recursive: true }, (err) => {
            if (err) {
              console.error(err)
            } else {
              console.log('/LUA/ is copied from ', currentworkspace, 'to ', targetDir)
            }
          })
        })
      })
    })
    .catch((err) => {
      console.log(err)
    })
  event.returnValue = 'success'
})

ipcMain.on('saveConfig', (event, value) => {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showMessageBox('工作目录未配置,请先打开工作目录')
    return
  }
  // console.log('@@', currentworkconfig, JSON.stringify(value))
  fs.writeFileSync(currentworkconfig, JSON.stringify(value))
  event.returnValue = 'success'
  // 同步导出设置到main.lua
  fs.mkdir(currentworkspace + '/LUA', { recursive: true }, (err) => {
    if (err) {
      dialog.showErrorBox('错误提示', '创建文件夹失败，请重试')
    }
  })
  let exportConfig = JSON.parse(fs.readFileSync(currentworkconfig))
  // console.log('@@@', exportConfig)

  configTextToFile(exportConfig)

  // exportConfig.main.content += `\r\ninit_modbus(` + settings.serialPort + `,` + settings.baudRate + `)`
  // exportConfig.main.content +=
  //   `\r\nset_screen_size(` +
  //   settings.width +
  //   `,` +
  //   settings.height +
  //   `,` +
  //   settings.screenOrientation +
  //   `)`
  // exportConfig.main.content += `\r\nset_screen_scale(` + settings.scale + `)`
  // // console.log('@@@@', exportConfig.main.content)
  // fs.writeFileSync(currentworkspace + '/LUA/main.lua', formatText(exportConfig.main.content))
  //
  // //写语言
  // let languages = settings.languages
  // if(languages) {
  //   let languagesLuaText ='set_language_map_font(1,1)\r\n'
  //   languages.forEach((langu, index) => {
  //     languagesLuaText += `set_language_map_font(${index+2}, `
  //       + langu.value.replace('.ttf', '').replace('font_', '') + `)\r\n`
  //   })
  //   languagesLuaText += 'set_language(get_language())'
  //   fs.writeFileSync(currentworkspace + '/LUA/main_language.lua', formatText(languagesLuaText))
  // }
})

ipcMain.on('importFont', () => {
  importFont()
})
ipcMain.on('importImage', () => {
  importImage()
})
ipcMain.on('importGif', () => {
  importGif()
})
ipcMain.on('importAudio', () => {
  importAudio()
})
ipcMain.on('importVideo', () => {
  importVideo()
})

ipcMain.on('refreshResource', (event) => {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showMessageBox(mainWindow, { message: '请先设置配置文件' })
    return
  }
  let fontList = []
  let imageList = []
  let audioList = []
  let videoList = []
  let gifList = []
  fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
    if (file.endsWith('.ttf')) {
      fontList.push(file)
    } else if (file.endsWith('.png')) {
      imageList.push({ name: file, fileData: fs.readFileSync(currentworkspace + '/HOMEI/' + file) })
    } else if (file.endsWith('.wav')) {
      audioList.push(file)
    } else if (file.endsWith('.video')) {
      videoList.push(file)
    } else if (file.endsWith('.gif')) {
      gifList.push({ name: file, fileData: fs.readFileSync(currentworkspace + '/HOMEI/' + file) })
    }
  })
  audioList.sort(function (x, y) {
    if (x != y) return x.replace('.wav', '') - y.replace('.wav', '')
    //	降序，升序则反之
    else {
      return 1
    }
  })
  imageList.sort(function (x, y) {
    if (x.name != y.name)
      return (
        x.name.replace('P', '').replace('.png', '') - y.name.replace('P', '').replace('.png', '')
      )
    //	降序，升序则反之
    else {
      return 1
    }
  })

  gifList.sort(function (x, y) {
    if (x.name != y.name)
      return (
        x.name.replace('G', '').replace('.gif', '') - y.name.replace('G', '').replace('.gif', '')
      )
    //	降序，升序则反之
    else {
      return 1
    }
  })
  // console.log('xx', imageList)
  // console.log('xx2', gifList)
  event.returnValue = {
    fontList: fontList,
    imageList: imageList,
    audioList: audioList,
    videoList: videoList,
    gifList: gifList
  }
})
//导入字库
function importFont() {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showMessageBox(mainWindow, { message: '请先设置配置文件' })
    return
  }
  dialog
    .showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [{ name: '支持的文件类型', extensions: ['ttf'] }]
    })
    .then(async (result) => {
      if (result.canceled) return
      await batchCopy(result.filePaths, 'font').then(() => {
        let fontList = []
        fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
          // console.log(file)
          if (file.endsWith('.ttf')) {
            fontList.push(file)
          }
        })
        mainWindow.webContents.send('loadFont', fontList)
      })
    })
}
// 在importImage函数中添加修复逻辑
const fixPNGHeader = (buffer) => {
  // 如果是真正的PNG文件，直接返回
  if (
    buffer.length > 8 &&
    buffer[0] === 0x89 &&
    buffer[1] === 0x50 &&
    buffer[2] === 0x4e &&
    buffer[3] === 0x47
  ) {
    return buffer
  }

  // 尝试识别常见图片格式并转换
  const sharp = require('sharp')
  try {
    return sharp(buffer).toFormat('png').toBuffer()
  } catch (err) {
    console.error('图片转换失败:', err)
    return null
  }
}
//导入图片
async function importImage() {
  if (!currentworkconfig) {
    dialog.showMessageBox({ message: '请先设置配置文件' })
    return
  }

  try {
    const result = await dialog.showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [{ name: '图片文件', extensions: ['png'] }]
    })

    if (result.canceled || result.filePaths.length === 0) return

    // 确保HOMEI目录存在
    const homeiDir = path.join(currentworkspace, 'HOMEI')
    if (!fs.existsSync(homeiDir)) {
      fs.mkdirSync(homeiDir, { recursive: true })
    }

    // 获取现有图片的最大编号
    const existingFiles = fs.readdirSync(homeiDir)
    const pngFiles = existingFiles.filter((file) => file.match(/^P(\d+)\.png$/i))
    let maxId = 0
    pngFiles.forEach((file) => {
      const match = file.match(/^P(\d+)\.png$/i)
      if (match) {
        const id = parseInt(match[1], 10)
        if (id > maxId) maxId = id
      }
    })

    // 处理每个选中的文件
    const importedFiles = []
    for (const filePath of result.filePaths) {
      try {
        // 读取文件
        const buffer = fs.readFileSync(filePath)

        // 使用sharp转换图片为PNG格式
        const sharp = require('sharp')
        const pngBuffer = await sharp(buffer).toFormat('png').toBuffer()

        // 生成新文件名
        const newFileName = `P${maxId + 1}.png`
        const destPath = path.join(homeiDir, newFileName)

        // 保存文件
        fs.writeFileSync(destPath, pngBuffer)

        importedFiles.push({
          name: newFileName,
          fileData: pngBuffer
        })

        maxId++
      } catch (err) {
        console.error(`处理文件 ${filePath} 失败:`, err)
      }
    }

    if (importedFiles.length === 0) {
      dialog.showMessageBox({ message: '没有成功导入任何图片' })
      return
    }

    // 获取当前所有图片（包括新导入的）
    const allImages = []
    fs.readdirSync(homeiDir).forEach((file) => {
      if (file.match(/^P\d+\.png$/i)) {
        allImages.push({
          name: file,
          fileData: fs.readFileSync(path.join(homeiDir, file))
        })
      }
    })

    // 按编号排序
    allImages.sort((a, b) => {
      const aNum = parseInt(a.name.match(/\d+/)[0], 10)
      const bNum = parseInt(b.name.match(/\d+/)[0], 10)
      return aNum - bNum
    })

    // 发送更新后的图片列表到前端
    mainWindow.webContents.send('loadImage', allImages)
  } catch (err) {
    console.error('导入图片过程中出错:', err)
    dialog.showErrorBox('错误', '导入图片失败: ' + err.message)
  }
}

//导入GIF
function importGif() {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showMessageBox(mainWindow, { message: '请先设置配置文件' })
    return
  }
  dialog
    .showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [{ name: '支持的文件类型', extensions: ['gif'] }]
    })
    .then(async (result) => {
      if (result.canceled) return

      await batchCopy(result.filePaths, 'gif').then(() => {
        let gifList = []
        // console.log(result.filePaths)
        fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
          // console.log('gif', file)
          if (file.endsWith('.gif')) {
            gifList.push({
              name: file,
              fileData: fs.readFileSync(currentworkspace + '/HOMEI/' + file)
            })
          }
        })
        console.log('abc', gifList)
        gifList.sort(function (x, y) {
          if (x.name != y.name)
            return (
              x.name.replace('G', '').replace('.gif', '') -
              y.name.replace('G', '').replace('.gif', '')
            )
          //	降序，升序则反之
          else {
            return 1
          }
        })
        console.log('cde', gifList)

        mainWindow.webContents.send('loadGif', gifList)
      })
    })
}

function importAudio() {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showMessageBox(mainWindow, { message: '请先设置配置文件' })
    return
  }
  dialog
    .showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [{ name: '支持的文件类型', extensions: ['wav'] }]
    })
    .then(async (result) => {
      if (result.canceled) return
      await batchCopy(result.filePaths, 'audio')
      let audioList = []
      fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
        if (file.endsWith('.wav')) {
          audioList.push(file)
        }
      })
      audioList.sort(function (x, y) {
        if (x != y) return x.replace('.wav', '') - y.replace('.wav', '')
        //	降序，升序则反之
        else {
          return 1
        }
      })
      mainWindow.webContents.send('loadAudio', audioList)
    })
}
//导入视频
function importVideo() {
  if (currentworkconfig == null || currentworkconfig === '') {
    dialog.showMessageBox(mainWindow, { message: '请先设置配置文件' })
    return
  }
  dialog
    .showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [{ name: '支持的文件类型', extensions: ['video'] }]
    })
    .then(async (result) => {
      if (result.canceled) return
      await batchCopy(result.filePaths, 'video').then(() => {
        let videoList = []
        fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
          // console.log(file)
          if (file.endsWith('.video')) {
            videoList.push(file)
          }
        })
        mainWindow.webContents.send('loadVideo', videoList)
      })
    })
}
ipcMain.on('deleteResource', (event, resourceType) => {
  let extensionName
  switch (resourceType) {
    case 'font':
      extensionName = '.ttf'
      break
    case 'image':
      extensionName = '.png'
      break
    case 'audio':
      extensionName = '.wav'
      break
    case 'video':
      extensionName = '.video'
      break
    case 'gif':
      extensionName = '.gif'
      break
  }
  fs.readdir(currentworkspace + '/HOMEI', function (err, files) {
    files.forEach(function (filename) {
      var src = path.join(currentworkspace + '/HOMEI', filename)
      fs.stat(src, function (err, st) {
        if (err) {
          throw err
        }
        // 判断是否为文件
        if (st.isFile()) {
          if (filename.endsWith(extensionName)) {
            fs.unlink(src, (err) => {
              if (err) throw err
              console.log('deleted:' + src)
            })
          }
        }
      })
    })
  })
})

ipcMain.on('deleteFile', (event, filename) => {
  fs.unlink(path.join(currentworkspace + '/HOMEI', filename), (err) => {
    if (err) {
      event.returnValue = 'fail'
    } else {
      event.returnValue = 'success'
    }
  })
})

// eslint-disable-next-line no-unused-vars
ipcMain.on('replacePng', (_event, fileName) => {
  dialog
    .showOpenDialog({
      properties: ['openFile'],
      filters: [{ name: '支持的文件类型', extensions: ['png'] }],
      title: '请选择图片',
      buttonLabel: '确定'
    })
    .then(async (result) => {
      if (result.canceled) return
      fs.copyFile(result.filePaths[0], path.join(currentworkspace, '/HOMEI', fileName), (err) => {
        if (err) console.log(err)
        let imageList = []
        fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
          if (file.endsWith('.png')) {
            imageList.push({
              name: file,
              fileData: fs.readFileSync(currentworkspace + '/HOMEI/' + file)
            })
          }
        })
        imageList.sort(function (x, y) {
          if (x.name != y.name)
            return (
              x.name.replace('P', '').replace('.png', '') -
              y.name.replace('P', '').replace('.png', '')
            )
          //	降序，升序则反之
          else {
            return 1
          }
        })
        mainWindow.webContents.send('loadImage', imageList)
      })
    })
})

ipcMain.on('replaceGif', (_event, fileName) => {
  dialog
    .showOpenDialog({
      properties: ['openFile'],
      filters: [{ name: '支持的文件类型', extensions: ['gif'] }],
      title: '请选择图片',
      buttonLabel: '确定'
    })
    .then(async (result) => {
      if (result.canceled) return
      fs.copyFile(result.filePaths[0], path.join(currentworkspace, '/HOMEI', fileName), (err) => {
        if (err) console.log(err)
        let gifist = []
        fs.readdirSync(currentworkspace + '/HOMEI').forEach((file) => {
          if (file.endsWith('.gif')) {
            gifist.push({
              name: file,
              fileData: fs.readFileSync(currentworkspace + '/HOMEI/' + file)
            })
          }
        })
        gifist.sort(function (x, y) {
          if (x.name != y.name)
            return (
              x.name.replace('G', '').replace('.gif', '') -
              y.name.replace('G', '').replace('.gif', '')
            )
          //	降序，升序则反之
          else {
            return 1
          }
        })
        mainWindow.webContents.send('loadGif', gifist)
      })
    })
})

ipcMain.on('pageSimulation', (_event, PageName) => {
  exportLua()
  cmd.run(`cd ${currentworkspace}`)
  cmd.run(`start "调试信息" cmd /C ${simulator} ${currentworkspace} ${PageName}`)
})

app.disableHardwareAcceleration()
